import {
  createRouter,
  createWebHistory,
  createWebHashHistory
} from 'vue-router'

import NProgress from 'nprogress'
import '/node_modules/nprogress/nprogress.css'
import LoginView from '../views/LoginView.vue'
import HomeView from '../views/home/HomeView.vue'
import { message } from 'ant-design-vue'
const router = createRouter({
  history: createWebHashHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'index',
      component: HomeView,
      redirect: '/dashboard', //  重定向
      children: [
        {
          path: 'dashboard',
          name: 'dashboard',
          component: () => import('../views/home/Dashboard.vue'),
          meta: {}
        }
        // {
        //   path: 'statistics',
        //   name: 'statistics',
        //   component: () => import('../views/home/Dashboard.vue')
        // }
      ]
    },
    {
      path: '/login',
      name: 'login',
      component: LoginView,
      meta: {
        notDetect: true
      }
    }
    // {
    //   path: '/about',
    //   name: 'about',
    //   component: () => import('../views/AboutView.vue')
    // }
  ]
})

router.beforeEach(function (to, from, next) {
  //
  //  登陆没
  //  本地存储里去拿数据

  NProgress.start()

  if (to.meta.notDetect) {
    //  不需要检测的页面 直接放行
    next()
  } else {
    //  需要检测的页面
    let now = +new Date()

    let { token, tokenExpired } = localStorage

    if (!token || tokenExpired <= now) {
      message.warn('您还未登陆,请登陆')
      setTimeout(() => {
        router.replace('/login')
      }, 1000)
      return
    }

    next()
  }
})

router.afterEach(() => {
  setTimeout(() => {
    NProgress.done()
  }, 300)
})

export default router
